package com.sinosoft.sm.message.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.sm.message.entity.MessageRecordEntity;
import com.sinosoft.sm.message.service.api.RecordService;
import com.sinosoft.sm.message.web.dto.RecordData;
import com.sinosoft.sm.system.common.entity.PaginationEntity;
import com.sinosoft.sm.system.common.utils.ajax.ResponseData;

/**
 * 发送记录控制层
 * @author leichao
 */
@Controller
@RequestMapping("record")
public class RecordController {

	@Autowired
	RecordService recordService;
	
	/**
	 * 根据查询条件获取用户信息
	 * 若recordData为空，则返回数据为空
	 * @param recordData	用户信息查询条件
	 * @return	回执数据
	 */
	@RequestMapping(value="getRecordByParamsService", method=RequestMethod.POST)
	@ResponseBody
	public ResponseData getRecordByParamsService(RecordData recordData) {
		if(recordData == null) {
			return new ResponseData(true, null);
		}
		PaginationEntity paginationEntity = null;
		paginationEntity = recordService.getRecord(recordData, recordData.getPage(), recordData.getRows());
		if(paginationEntity == null) {
			return new ResponseData(true, null);
		} else {
			ResponseData response = new ResponseData(true, paginationEntity.getTotal(), getRecordDatas(paginationEntity.getData()));
			return response;
		}
	}
	
	@RequestMapping(value="addRecordService", method=RequestMethod.POST)
	@ResponseBody
	public ResponseData addRecordService(RecordData recordData){
		if(recordData == null){
			return new ResponseData(true, null);
		}
		try {
			boolean result = recordService.addMessageRecord(recordData.toMessageRecordEntity());
			if(result){
				return new ResponseData(result, null);
			}else{
				return new ResponseData(result,null,"发送失败，若多次失败请联系管理员", null);
			}
		} catch (Exception e) {
			return new ResponseData(false, null, e.getMessage(), null);
		}
	}
	
	private List<RecordData> getRecordDatas(Object object) {
		List<MessageRecordEntity> records = (List<MessageRecordEntity>)object;
		int size = records.size();
		List<RecordData> messageRecordDatas = new ArrayList<RecordData> ();
		for(int i=0; i<size; i++) {	//	循环将实体数据转换为传输数据
			RecordData recordData = new RecordData();
			recordData.toRecordData(records.get(i));
			messageRecordDatas.add(recordData);
		}
		return messageRecordDatas;
	}
}
